package br.com.jr.arq.service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.annotation.Resource;

import org.springframework.dao.DataAccessException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Repository;

import br.com.jr.arq.dao.UserDao;
import br.com.jr.arq.dominio.Authority;
import br.com.jr.arq.dominio.Usuario;

@Repository("userUserDetailsService")
public class UserUserDetailsService implements UserDetailsService {
	
	@Resource
	private UserDao userDao;

	public UserUserDetailsService() {
	}

	public UserUserDetailsService(UserDao userDao) {
		this.userDao = userDao;
	}

	public UserDetails loadUserByUsername(String userName) 
			throws UsernameNotFoundException, DataAccessException {

		Usuario user;
		List<String> authorityList = new ArrayList<String>();
		String authority;
		try {
			user = userDao.getUserByUserName(userName);
		} catch (Exception e) {
			throw new UsernameNotFoundException("Erro.");
		}
		
		Set<Authority> authoritySet = user.getAuthoritySet();
		Iterator<Authority> authoritySetIterator = authoritySet.iterator();
		
		while(authoritySetIterator.hasNext()) {
			authority=authoritySetIterator.next().getAuthority();
			authorityList.add(authority);
		}
		
		user.setUserAuthorities(authorityList);
		return (UserDetails) user;
	}
	
}